package com.jinlejia.erp.ui.common;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.BuildConfig;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.utils.DbUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;

/**
 *
 */
public class WellcomeActivity extends AppCompatActivity {

    Handler handler = new Handler();
    private TextView tv_Edition;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wellcome);
        tv_Edition = (TextView) findViewById(R.id.tv_Edition);
        tv_Edition.setText(String.format("©  %s", BuildConfig.VERSION_NAME));
        loadAd(this);
    }
    private volatile long startTime;
    private void loadAd(final Context context){
        startTime = System.currentTimeMillis();
        OkHttpUtils.get()
                .url(ApiConfig.ADVERT)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        delayed(-1,null,null); //如果网络请求失败
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        String codeStr = String.valueOf(response.get("code"));
                        int code = 0;
                        try {
                            code = Integer.parseInt(codeStr);
                        }catch (Exception ignored){
                        }
                        if (code==200){
                            Object data = response.get("data");
                            if (data==null){ //如果没有数据
                                delayed(-1,null,null);
                                return;
                            }
                            String dataStr = String.valueOf(data);
                            JSONObject json = null;
                            try{
                                json = JSON.parseObject(dataStr);
                            }catch (Exception ignored){
                            }
                            if (json!=null){
                                int isShow = json.getIntValue("isShow");
                                if (isShow==0){ //如果不需要展示
                                    delayed(-1,null,null);
                                    return;
                                }
                                String showSeconds = json.getString("showSeconds");
                                long showSeconds_ = Long.parseLong(showSeconds);
                                String url = json.getString("url");
                                String detailUrl = json.getString("detailUrl");
                                url = ApiConfig.MAGEHEADER_URL() + url;
                                detailUrl = ApiConfig.MAGEHEADER_URL() + detailUrl;
                                delayed(showSeconds_,url,detailUrl);
                            }else {
                                delayed(-1,null,null);
                            }
                        }else { //当服务器接口数据没有正确返回时，进行延迟跳转
                            delayed(-1,null,null);
                        }
                    }
                });
    }

    private void delayed(final long showSeconds,final String adUrl,final String detailUrl){
        long time = System.currentTimeMillis() - startTime; //请求时间
        long showTime = TimeUnit.SECONDS.toMillis(3); //过度时间
        long spaceTime = 0;
        if (time<showTime){
            spaceTime = showTime-time; //去除请求的时间
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                if (null != DbUtil.getDB(WellcomeActivity.this).single().queryById(200, SaveCookieBean.class) &&
                        null != DbUtil.getDB(WellcomeActivity.this).single().queryById(202, SaveCookieBean.class).getPin())
                {
                    intent.setClass(WellcomeActivity.this,MainActivity.class);
                    intent.putExtra("flag", "main");
                } else {
                    intent.setClass(WellcomeActivity.this, LoginActivity.class);
                    intent.putExtra("flag", "wellcome");
                }
                if (showSeconds!=-1){ //如果需要展示，并且达到展示的前提
                    intent.putExtra("adUrl",adUrl);
                    intent.putExtra("detailUrl",detailUrl);
                    intent.putExtra("showSeconds",showSeconds);
                    intent.setClass(WellcomeActivity.this, ADActivity.class);
                }
                startActivity(intent);
                finish();
            }
        }, spaceTime);
    }
}
